from info import redis_store
from info.models import User, News, Category
from info.modules.index import index_blueprint
from flask import render_template, current_app, session, jsonify, request, g

from info.utils.commons import user_login_data
from info.utils.response_code import RET


@index_blueprint.route("/newslist",methods=["GET"])
def newList():
    # cid(分类), page, per_page

    cid = request.args.get("cid", '1')
    page = request.args.get("page",1)
    per_page = request.args.get("per_page", 10)
    # print(cid)

    try:
        filters =[]
        if cid != "1":
            filters.append(News.category_id == cid)
        pageinate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(int(page), int(per_page), False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="新闻数据获取失败")
    total_page=pageinate.pages
    items=pageinate.items
    news_list=[]
    for news in items:
        news_list.append(news.to_dict())
    return jsonify(errno=RET.DBERR,errmsg="获取新闻成功",totalPage=total_page,newsList=news_list)


@index_blueprint.route('/')
@user_login_data
def hello_world():  # put application's code here
    # redis_store.set("name","zhangsan")
    # user_id = session.get("user_id")
    # # print(user_id)
    # user = None
    # try:
    #     user = User.query.get(user_id)
    # except Exception as e:
    #     current_app.logger.error(e)
    # 查询热榜
    news = None
    try:
        news = News.query.order_by(News.clicks.desc()).limit(10).all()
    except Exception as e:
        current_app.logger.error(e)
        # print(e)
    news_list = []
    for item in news:
        news_list.append(item.to_dict())
    # print(news_list)
    # 查询分裂
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询分类失败")
    category_list = []
    for item in categories:
        category_list.append(item.to_dict())
    data = {
        "user_info": g.user.to_dict() if g.user else "",
        "news_list": news_list,
        "category_list": category_list
    }

    return render_template("news/index.html", data=data)


@index_blueprint.route("/favicon.ico")
def get_web_logo():
    return current_app.send_static_file("news/favicon.ico")
